package com.lovely602.ai.alibaba.controller.chat;


import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author lizhixing
 */
@RestController
@RequestMapping(value = "/chat/model")
public class ChatModelController {

    private static final String DEFAULT_PROMPT = """
            你作为一名JAVA程序员，你的名字叫老李。
            回答时告知你的姓名。
            回答时返回使用的模型信息。
            """;

    private final DashScopeChatModel chatModel;

    public ChatModelController(DashScopeChatModel chatModel) {

        this.chatModel = chatModel;
    }

    @GetMapping(value = "/call")
    public String call(@RequestParam(value = "msg", required = true) String msg) {

        UserMessage userMessage = new UserMessage(msg);

        SystemMessage systemMessage = new SystemMessage(DEFAULT_PROMPT);

        DashScopeChatOptions chatOptions = DashScopeChatOptions.builder()
                .withTopP(0.7)
                .withTopK(10)
                .withTemperature(0.7)
                .withModel("qwen3-4b")
                .build();

        List<Message> messages = new ArrayList<>();
        messages.add(userMessage);
        messages.add(systemMessage);

        Prompt prompt = new Prompt(messages, chatOptions);

        return chatModel.call(prompt).getResult().getOutput().getText();

    }

    @GetMapping(value = "/stream", produces = "text/html;charset=UTF-8")
    public Flux<String> stream(@RequestParam(value = "msg", required = true) String msg) {

        UserMessage userMessage = new UserMessage(msg);

        SystemMessage systemMessage = new SystemMessage(DEFAULT_PROMPT);

        DashScopeChatOptions chatOptions = DashScopeChatOptions.builder()
                .withTopP(0.7)
                .withTopK(10)
                .withTemperature(0.7)
                .withModel("qwen3-0.6b")
                .build();

        List<Message> messages = new ArrayList<>();
        messages.add(userMessage);
        messages.add(systemMessage);

        Prompt prompt = new Prompt(messages, chatOptions);

        return chatModel.stream(prompt).map(response -> (response.getResult() == null || response.getResult().getOutput() == null
                || response.getResult().getOutput().getText() == null) ? ""
                : response.getResult().getOutput().getText());

    }

}
